import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/models/bill_detail_model.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 详细账单列表页面
class BillDetailScreen extends ConsumerWidget {
  final int userId;
  final int type;
  final int secondClassifyId;
  final String date;
  final String title;

  const BillDetailScreen({
    Key? key,
    required this.userId,
    required this.type,
    required this.secondClassifyId,
    required this.date,
    required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final billDetailAsync = ref.watch(billDetailListProvider((userId, type, secondClassifyId, date)));

    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        backgroundColor: AppTheme.primaryColor,
        foregroundColor: Colors.white,
      ),
      body: billDetailAsync.when(
        data: (billDetailData) {
          if (billDetailData == null) {
            return _buildEmptyState();
          }
          return _buildBillDetailList(billDetailData);
        },
        loading: () => _buildLoadingState(),
        error: (error, stack) => _buildErrorState(error.toString()),
      ),
    );
  }

  /// 构建账单详情列表
  Widget _buildBillDetailList(BillDetailData billDetailData) {
    return Column(
      children: [
        // 总计信息
        _buildSummaryCard(billDetailData),
        // 账单列表
        Expanded(
          child: ListView.builder(
            padding: EdgeInsets.all(16.w),
            itemCount: billDetailData.billData.length,
            itemBuilder: (context, index) {
              final dayData = billDetailData.billData[index];
              return _buildDaySection(dayData);
            },
          ),
        ),
      ],
    );
  }

  /// 构建总计信息卡片
  Widget _buildSummaryCard(BillDetailData billDetailData) {
    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildSummaryItem('总收入', billDetailData.allIncomeSum, Colors.green),
          Container(
            width: 1,
            height: 30.h,
            color: Colors.grey[300],
          ),
          _buildSummaryItem('总支出', billDetailData.allExpendSum, Colors.red),
        ],
      ),
    );
  }

  /// 构建总计项目
  Widget _buildSummaryItem(String label, double amount, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[600],
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          '¥${amount.toStringAsFixed(2)}',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  /// 构建每日账单区块
  Widget _buildDaySection(BillDayData dayData) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 日期头部
          _buildDayHeader(dayData.itemData),
          // 账单列表
          ...dayData.itemList.map((bill) => _buildBillItem(bill)).toList(),
        ],
      ),
    );
  }

  /// 构建日期头部
  Widget _buildDayHeader(BillItemData itemData) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppTheme.primaryColor.withOpacity(0.1),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12.r),
          topRight: Radius.circular(12.r),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            itemData.date,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.bold,
              color: AppTheme.primaryColor,
            ),
          ),
          Row(
            children: [
              if (itemData.incomeSum > 0) ...[
                Text(
                  '收入: ¥${itemData.incomeSum.toStringAsFixed(2)}',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.green,
                  ),
                ),
                SizedBox(width: 8.w),
              ],
              if (itemData.expendSum > 0) ...[
                Text(
                  '支出: ¥${itemData.expendSum.toStringAsFixed(2)}',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.red,
                  ),
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }

  /// 构建账单条目
  Widget _buildBillItem(BillItem bill) {
    final isIncome = bill.type == 1;
    final color = isIncome ? Colors.green : Colors.red;
    final prefix = isIncome ? '+' : '-';

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Colors.grey[200]!,
            width: 0.5,
          ),
        ),
      ),
      child: Row(
        children: [
          // 图标
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Icon(
              isIncome ? Icons.arrow_downward : Icons.arrow_upward,
              color: color,
              size: 20.sp,
            ),
          ),
          SizedBox(width: 12.w),
          // 账单信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  bill.name ?? '未分类',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                if (bill.remark?.isNotEmpty == true) ...[
                  SizedBox(height: 2.h),
                  Text(
                    bill.remark!,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
                SizedBox(height: 2.h),
                Text(
                  '${bill.bankName ?? ''} • ${bill.merchantName ?? ''}',
                  style: TextStyle(
                    fontSize: 11.sp,
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
          // 金额
          Text(
            '$prefix¥${bill.money.toStringAsFixed(2)}',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.receipt_long_outlined,
            size: 64.sp,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16.h),
          Text(
            '暂无账单数据',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return const Center(
      child: CircularProgressIndicator(),
    );
  }

  /// 构建错误状态
  Widget _buildErrorState(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64.sp,
            color: Colors.red[400],
          ),
          SizedBox(height: 16.h),
          Text(
            '加载失败',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            error,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[500],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}